<?php

class DealController extends Controller
{

	public $layout='//layouts/column2';
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('list' , 'view', 'index'),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('create', 'update', 'uploadImg', 'deleteimg', 'coupon', 'print'),
				'roles'=>array('user'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionIndex(){
		
		$this->render('index',array());	
	}

	public function actionList() {
		$criteria = new CDbCriteria;
		if(isset($_GET['id'])) {
			$criteria->condition = 'is_approved = "1" AND deal_category_id = :cat_id';
			$criteria->params = array(':cat_id'=>(int)$_GET['id']);	
		}
		
		$dataProvider=new CActiveDataProvider('Deal', array('criteria'=>$criteria));
		$this->render('list',array(
			'dataProvider'=>$dataProvider,
		));
	}
	
	public function actionView() {
		if(isset($_GET['id']) && ($model = Deal::getModel((int)$_GET['id']))) {
		
			$this->render('view',array(
				'model'=>$model,
			));
		} else 
			throw new CHttpException(404,'The requested page does not exist.');	
	}
	
	public function actionCreate() {
		$user = Yii::app()->user->getModel();
		
		$companies = Company::getByUserId($user->id);
		if($companies) {
			$model = new Deal;
			
			if(isset($_POST['Deal'])) {
				$user = Yii::app()->user->getModel();
				$model->user_id = $user->id;
				
				$model->attributes=$_POST['Deal'];
				if($model->save()) {
					User::sendToAdmin('new_deal');
					Yii::app()->user->setFlash('success', Configuration::getValue('success_new_deal_save'));
					$this->redirect(array('update','id'=>$model->id));
				}
			}
			$this->render('create',array(
				'model'=>$model,
				'companies'=>$companies,
			));	
		} else {
			Yii::app()->user->setFlash('notice', 'Необходимо создать компанию');
			$this->redirect('/company/create');
		}	
	}
	
	public function actionUpdate() {
		if(isset($_GET['id'])) {
			$user = Yii::app()->user->getModel();
			if($model = Deal::getByUserAndId($user->id ,(int)$_GET['id'])) {
				$companies = Company::getByUserId($user->id);
				
				if(isset($_POST['Deal'])) {
					
					$model->attributes=$_POST['Deal'];
					if($model->save()) {
						Yii::app()->user->setFlash('success', 'Акция успешно сохранена');
						$this->redirect(array('update','id'=>$model->id));
					}
				}
				
				$this->render('update',array(
					'model'=>$model,
					'companies'=>$companies,
				));	
			} else
				throw new CHttpException(404,'The requested page does not exist.'); 
		} else
			throw new CHttpException(404,'The requested page does not exist.');
			
	}
	
	/**
	 * Upload img
	 */
	public function actionUploadImg() {
		$response = array();
		$form = new AjaxUploadImageForm;
       	if( isset($_POST['AjaxUploadImageForm'], $_POST['deal_id']) && 
       		($deal = Deal::model()->findByPk((int)$_POST['deal_id'])))
        {
            $form->attributes = $_POST['AjaxUploadImageForm'];
            if($form->validate()) {
            	$form->image = CUploadedFile::getInstance($form,'image');
            	$model = new Img;
            	$model->_file = $form->image;
            	$model->_file;
            	$model->loadImage();
            	
	            if($model->save(false)) {
	            	$dealImg = new DealImg;
	            	$dealImg->deal_id = $deal->id;
	            	$dealImg->img_id = $model->id;
	            	$dealImg->save(false);
	            	$response['success'] = array('id'=>$model->id, 'name'=>$model->name);
	            }
            }else {
            	$response = array('errorSummary'=>'Неверный формат или размер картинки'); //CHtml::errorSummary($form)
            }
        }
        
//		if (!$response) {
//			$response = array('error'=>'error');
//			//$response = array('error'=>$this->renderPartial('_image_form', array('model' => new AjaxUploadImageForm),true, true));	
//		}
		
//      	foreach ($response as $key=>$val) {
//			$response[$key] = rawurlencode($response[$key]);
//		}
//		
		echo CJSON::encode($response);
		die;
	}
	
	public function actionDeleteimg() {
		$result = '';
		if(isset($_POST['i']) && ($img = Img::model()->findByPk((int)$_POST['i']))) {
			$img->deleteFile();
			if($img->delete()) 
				$result = $_POST['i'];
		}
		echo $result;
		die;
	}
	
	public function actionCoupon() {
		if(isset($_GET['id']) && ($model = Deal::getModel((int)$_GET['id']))) {
			$user = Yii::app()->user->getModel();
			$coupon = UserDeal::getByUserDeal($user->id, $model->id);
			if(!$coupon) {
				if($user->balance < $model->price) {
					Yii::app()->user->setFlash('error', 'У Вас не хватает баллов для получения акции');
					$this->redirect(array('/deal/'. $model->id));		
				}

				$coupon = UserDeal::setCoupon($user->id, $model->id);
				$user->updateBalance(-$model->price);				
			}
		
			$this->render('coupon',array(
				'model'=>$model, 'coupon'=>$coupon, 'user'=>$user
			));
		} else 
			throw new CHttpException(404,'The requested page does not exist.');			
	}
	
	public function actionPrint() {
		$this->layout = 'print';
		if(isset($_GET['id']) && ($model = Deal::getModel((int)$_GET['id']))) {
			$user = Yii::app()->user->getModel();
			$coupon = UserDeal::getByUserDeal($user->id, $model->id);
			if($coupon) {
				$this->render('print',array(
				'model'=>$model, 'coupon'=>$coupon, 'user'=>$user
				));
			} else 
				throw new CHttpException(404,'The requested page does not exist.');
		} else 
			throw new CHttpException(404,'The requested page does not exist.');			
	}
}
